<template>
  <div v-loading="loading">
    <FixedOperation>
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <el-button
              :disabled="formData.createBy !== userStore.userInfo.userName"
              type="primary"
              @click="handleUpdate"
              >编辑报告</el-button
            >
            <el-button
              :disabled="formData.createBy !== userStore.userInfo.userName"
              plain
              type="primary"
              @click="handleDelete"
              >删除报告</el-button
            >
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container">
      <el-row :gutter="20">
        <el-col :span="24" class="m-b-6">
          <el-card
            class="border-solid border-1 border-gray-300 rounded-2xl pt-6"
          >
            <div class="w-12/24 inline-block">
              <div class="text-2xl pb-4 font-bold w-12/24">
                <div class="mb-10px">
                  {{ formData.createName }}
                  <span v-if="formData.reportType">(工作</span>
                  <dict-drop
                    style="display: inline-block"
                    :options="report_type"
                    :value="formData.reportType"
                  ></dict-drop
                  >)
                </div>
                <span>{{
                  parseTime(formData.reportStartDate, '{y}-{m}-{d}')
                }}</span>
                <span
                  v-if="formData.reportEndDate && formData.reportType !== '0'"
                  >至{{
                    parseTime(formData.reportEndDate, '{y}-{m}-{d}')
                  }}</span
                >
              </div>
            </div>
            <div class="w-12/24 inline-block">
              <div class="text-xl pb-4 w-12/24">
                <span class="text-gray-400">状态:</span>
                <dict-drop
                  style="display: inline-block"
                  :options="review_status"
                  :value="formData.reviewStatus"
                ></dict-drop>
              </div>
              <div class="flex">
                <el-tooltip
                  :disabled="showTip"
                  class="box-item"
                  effect="dark"
                  :content="formData.reviewUserName"
                  placement="top"
                >
                  <div
                    class="text-xl pb-4 w-12/24 truncate"
                    @mouseenter="spanMouseenter($event)"
                  >
                    <span class="text-gray-400">批阅人员:</span
                    >{{ formData.reviewUserName }}
                  </div>
                </el-tooltip>
                <el-tooltip
                  :disabled="showTip"
                  class="box-item"
                  effect="dark"
                  :content="formData.copyUserName"
                  placement="top"
                >
                  <div
                    class="text-xl pb-4 w-12/24 truncate"
                    @mouseenter="spanMouseenter($event)"
                  >
                    <span class="text-gray-400">抄送人员:</span
                    >{{ formData.copyUserName }}
                  </div>
                </el-tooltip>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="24">
          <el-card
            class="border-solid border-1 border-gray-300 rounded-2xl pt-6"
            style="min-height: 81vh"
          >
            <TitleName
              title="工作总结"
              icon="i-carbon-bookmark-filled"
              :titleStyle="{ color: '#000' }"
              class="pb-3"
            ></TitleName>
            <div
              class="mb-6 bg-slate-100 p-4 text-14px"
              v-html="formData.summary"
            />
            <div v-if="formData.reportType !== '0'">
              <TitleName
                title="工作计划"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
                class="pb-3"
              ></TitleName>
              <div
                class="mb-6 bg-slate-100 p-4 whitespace-pre-wrap text-14px"
                v-html="formData.plan"
              />
            </div>
            <div v-if="formData.id" class="mb-6">
              <AppendixList :tableParam="followUpListParams" />
            </div>
            <TitleName
              title="批阅记录"
              icon="i-carbon-bookmark-filled"
              :titleStyle="{ color: '#000' }"
              class="pb-3"
            ></TitleName>
            <ReviewRecord
              :reviewRecordParams="{
                limits: formData.reviewUserArr
              }"
              :workReportId="formData.id"
              @sending="sending"
            />
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script setup name="WorkReportDetails">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useTagsViewStore from '@/store/modules/tagsView'
import { getWorkReport, delWorkReport } from '@/api/workReport/index'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
import { getTreeNodeByParam } from '@/utils/commo'
import AppendixList from '@/businessComponents/AppendixList'
import ReviewRecord from './reviewRecord'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const { proxy, type } = getCurrentInstance()
const { report_type, review_status } = proxy.useDict(
  'report_type',
  'review_status'
)

const props = defineProps({
  workReportData: {
    type: Object,
    require: false
  },
  workReportId: {
    type: [Number, String],
    require: false
  }
})
const prUrl = ref(null)
const data = reactive({
  loading: false,
  formData: {
    attachment: []
  },
  userOption: { publishUsers: [] }, //人员选择下拉
  followUpListParams: {}
})
let { loading, formData, userOption, followUpListParams } = toRefs(data)

watch(
  [() => route.query.workReportId, () => props.workReportId],
  async () => {
    if (
      (route.query.workReportId && route.name == type.name) ||
      props.workReportId
    ) {
      let id = route.query.workReportId || props.workReportId
      await getFormData(id)
    }
  },
  {
    immediate: true
  }
)

const showTip = ref(false)
function spanMouseenter(ev) {
  if (ev.target.clientWidth < ev.target.scrollWidth) {
    showTip.value = false
  } else {
    showTip.value = true
  }
}

/** 获取详情
 * @param {number}  id 表单id
 */
async function getFormData(id) {
  loading.value = true
  let res = await getWorkReport(id)
  loading.value = false
  if (res.code == 200) {
    let resData = {}
    resData = res.data
    formData.value = resData

    followUpListParams.value = {
      businessId: formData.value.id, //业务id
      busineName: '', //业务名称
      tableName: 'sys_work_report' //业务类型  biz_customer  客户页面  ord_project  项目  ord_order订单
    }
  }
}

/**修改按钮操作 */
function handleUpdate(row) {
  console.log('row', row)
  goTo('/rsgl/other/workReportForm', { workReportId: formData.value.id })
}
/** 删除按钮操作 */
function handleDelete(row) {
  const workReportIds = formData.value.id
  let msgTile = ''
  if (formData.value.reportEndDate && formData.value.reportType !== '0') {
    msgTile = `${formData.value.createName}${proxy.parseTime(
      formData.value.reportStartDate,
      '{y}-{m}-{d}'
    )}至${proxy.parseTime(
      formData.value.reportEndDate,
      '{y}-{m}-{d}'
    )}的工作${proxy.selectDictLabel(
      report_type.value,
      formData.value.reportType
    )}`
  } else {
    msgTile = `${formData.value.createName}${proxy.parseTime(
      formData.value.reportStartDate,
      '{y}-{m}-{d}'
    )}的工作${proxy.selectDictLabel(
      report_type.value,
      formData.value.reportType
    )}`
  }
  proxy.$modal
    .confirm(`是否删除${msgTile}？`)
    .then(function () {
      return delWorkReport(workReportIds)
    })
    .then(() => {
      proxy.$modal.msgSuccess('删除成功')
      handleReturn()
    })
    .catch(() => {})
}
function goTo(url, data) {
  router.push({ path: url, query: data })
}
/**
 * 根据当前用户id转为uuid（id前加u）
 * @param val 输入用户的id
 * @param fieldName 需要赋值的字段
 * @param selectArr 用户的字典
 */
async function getDefaultUserInfo(val, fieldName, selectArr) {
  let userTree = await commonStore.getUseTreeData()
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(userTree, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      formData.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(userTree, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}
// 发送批阅成功时
async function sending(e) {
  // console.log('发送==》', e)
  if (e.code == 200) {
    await getFormData(e.data.reportId)
  }
}
// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

function init() {}
init()
</script>
<style lang="scss" scoped>
:deep(img) {
  width: 100%;
}
</style>
